const fs = require('fs'),
      path = require('path'),
      moment = require('moment'),
      stringify = require('./json').stringify;

const openJson = (...filePath) => JSON.parse(fs.readFileSync(path.resolve(...filePath), 'utf-8'));

const saveJson = (obj, ...filePath) => fs.writeFileSync(path.resolve(...filePath), stringify(obj));

const saveLog = message => {
    if(process.env.SAVE_LOG === 'false') return;

    const filename = `${moment().format('YYYY-MM-DD')}.log`,
          dirPath = path.resolve(__dirname, '..', 'log'),
          filePath = path.resolve(dirPath, filename);

    if(!fs.existsSync(dirPath)) fs.mkdirSync(dirPath);
    if(!fs.existsSync(filePath)) fs.writeFileSync(filePath, '<<< SERVER LOG >>>');
    fs.appendFileSync(filePath, '\n' + message);
};

module.exports = {
    openJson,
    saveJson,
    saveLog
};
